package com.example.myapplication3;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ConfigActivity extends AppCompatActivity implements Runnable {

    private static final String TAG = "Rate";

    private EditText dollarText, euroText, wonText; // 声明变量
    private TextView onlineText;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_config);

        // 处理 Intent 数据（从上一个 Activity 传递过来的汇率）
        Intent intent = getIntent();
        float dollar = intent.getFloatExtra("dollar_rate_key", 0.0f);
        float euro = intent.getFloatExtra("euro_rate_key", 0.0f);
        float won = intent.getFloatExtra("won_rate_key", 0.0f);

        Log.i(TAG, "onCreate: dollar=" + dollar);
        Log.i(TAG, "onCreate: euro=" + euro);
        Log.i(TAG, "onCreate: won=" + won);

        // 初始化 View
        dollarText = findViewById(R.id.input_dollar_config); // 确保布局文件中有对应的 ID
        euroText = findViewById(R.id.input_euro_config);
        wonText = findViewById(R.id.input_won_config);
        onlineText=findViewById(R.id.show_online);

        // 将数据设置到 EditText
        dollarText.setText(String.valueOf(dollar));
        euroText.setText(String.valueOf(euro));
        wonText.setText(String.valueOf(won));

        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(TAG, "handleMessage:接收消息");
                if (msg.what == 8) {
                    String str = (String) msg.obj;
                    Log.i(TAG, "handleMessage:str" + str);
                    onlineText.setText(str);
                }
                super.handleMessage(msg);
            }
        };



    }
public void onClick(View btn)
{
    Thread t = new Thread(this);
    t.start();

//    Thread t2=new Thread(new Runnable() {
//        @Override
//        public void run() {
//            Log.i(TAG,"run:t2 222222");
//        }
//    });
//    t2.start();
//
//    Thread t3 =new Thread(()->{ Log.i(TAG,"run:t3 3333333");});//简写方法（）等效run()
//    t3.start();

}
    public void save(View btn) {
        Log.i(TAG, "save:");
        //重新获新的输入公
        String dollarStr = dollarText.getText().toString();
        String euroStr = euroText.getText().toString();
        String wonStr = wonText.getText().toString();
        Log.i(TAG, "save: dollarStr=" + dollarStr);
        Log.i(TAG, "save: eurostr=" + euroStr);
        Log.i(TAG, "save: wonStr=" + wonStr);

        Intent intent = getIntent();
        //放入数据到intent
        Bundle bundle = new Bundle();
        bundle.putFloat("key_dollar2", Float.parseFloat(dollarStr));
        bundle.putFloat("key_euro2", Float.parseFloat(euroStr));
        bundle.putFloat("key_won2", Float.parseFloat(wonStr));
        intent.putExtras(bundle);
        setResult(666, intent);

        finish();
    }


    public void run() {
        Log.i(TAG, "run:run()... .......");
        //发消息

        URL url = null;//获取网络数据
        try {

            url = new URL("https://www.federalreserve.gov/releases/h10/current/");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            InputStream in = http.getInputStream();

            String html = inputStream2String(in);
            Log.i(TAG, "run: html=" + html);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        Message msg=handler.obtainMessage(8,"https://www.federalreserve.gov/releases/h10/current/");//what取件码,obj快递
        handler.sendMessage(msg);

        try {
            Thread.sleep(3000);
            Document doc=  Jsoup.connect("https://www.federalreserve.gov/releases/h10/current/").timeout(10000).get();

            String releaseDate = doc.selectFirst("#content > table > tbody > tr:nth-child(4) > td:nth-child(3)").text();
            Message msg2 = handler.obtainMessage(8, "最新更新：" + releaseDate);
            handler.sendMessage(msg2);//
            // 获取发布日期
            Elements tables=doc.getElementsByTag("table");
            Element table2=tables.get(0);
            Elements trs=table2.getElementsByTag("tr");
            trs.remove(0);
            for(Element tr:trs) {

                Elements tds = tr.children();
                Element td1 = tds.get(1);
                Element td2 = tds.get(6);

                String moneyname = td1.text();
                String rate = td2.text();
                Log.i(TAG, "run:" + moneyname + "==>" + rate);

                float r= 100/Float.parseFloat(rate);


            }
        }catch(IOException e)
                    {throw new RuntimeException(e);}
            catch(InterruptedException e)
            {throw new RuntimeException(e);}







    }



    private String inputStream2String (InputStream inputStream)//转化为字符串
            throws IOException
    {
    final int bufferSize = 1024;
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    Reader in = new InputStreamReader(inputStream, "utf-8");
        while (true) {
        int rsz = in.read(buffer, 0, buffer.length);

        if (rsz < 0)
            break;
        out.append(buffer, 0, rsz);
    }
        return out.toString();
}
}